package cn.hd01.service.impl;

import cn.hd01.repository.StyleRepository;
import cn.hd01.repository.entity.Style;
import cn.hd01.service.StyleService;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cyb
 * @date 2017/5/22.
 */
@Service
public class StyleServiceImpl extends BaseServiceImpl<Style, Integer> implements StyleService {

    private final StyleRepository repository;

    public StyleServiceImpl(StyleRepository repository) {
        super(repository);
        this.repository = repository;
    }

    @Override
    public Page<Style> findAll(final Style style, Pageable pageable) {
        if (style == null) {
            return repository.findAll(pageable);
        }

        return repository.findAll(Specifications.where(new Specification<Style>() {
            @Override
            public Predicate toPredicate(Root<Style> r, CriteriaQuery<?> q, CriteriaBuilder
                    cb) {
                List<Predicate> predicates = new ArrayList<>();

                if (StringUtils.hasText(style.getName())) {
                    predicates.add(cb.like(r.get("name").as(String.class), "%" + style.getName() + "%"));
                }
                
                if (style.getType() != null) {
					predicates.add(cb.equal(r.get("type").as(Integer.class), style.getType()));
                }
                

                if (style.getHot() != null) {
					predicates.add(cb.equal(r.get("hot").as(Boolean.class), style.getHot()));
                }
                
                if (style.getRecommend() != null) {
					predicates.add(cb.equal(r.get("recommend").as(Boolean.class), style.getRecommend()));
                }

                return cb.and(predicates.toArray(new Predicate[0]));
            }
        }), pageable);
    }

    @Override
    public void updateCoverPic(Integer id, Integer picId) {
        repository.updateCoverPic(picId, id);
    }

    @Override
    public void updateHot(Integer id, Boolean hot) {
        repository.updateHot(id, hot);
    }

    @Override
    public void updateRecommend(Integer id, Boolean recommend) {
        repository.updateRecommend(id, recommend);
    }
}
